package com.saltedfish.tool.util;



import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.saltedfish.tool.model.UpdateVersionInfo;

import java.io.File;

import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.popwindow.AlertButtonDialog;

/**
 * 作者：lenovo on 2016/12/14
 */
public class DownLoadUtils {

    public void checkForUpdateSuccess(Context context,final UpdateVersionInfo versionInfo) {
        if (versionInfo != null && versionInfo.isHasNewVersion()) {
            if (!TextUtils.isEmpty(versionInfo.getApkUrl())) {
                //0:表示需要更新 1：表示最新 2 表示客户端大于服务器版本（视为不需要跟新）
                AlertButtonDialog dialog = new AlertButtonDialog(context);
                dialog.builder();
                dialog.setTitle("版本更新");
                dialog.setMsg("检测到最新版本，是否去下载安装？");
                dialog.setPositiveButton("确定",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(
                                    View v) {
                                if (Build.VERSION.SDK_INT >= 23) {
                                    if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context,
                                            Manifest.permission.READ_EXTERNAL_STORAGE) ||
                                            PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context,
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                        DownLoadUtils.download(
                                                context,
                                                versionInfo.getApkUrl(),
                                                "咸鱼Flag");
                                    } else {
                                       // ToastUtils.showMessage(context, "存储权限被禁止，请前往系统设置->应用管理->咸鱼Flag下权限管理开启存储权限");
                                        return;
                                    }
                                } else {
                                    DownLoadUtils.download(
                                            context,
                                            versionInfo.getApkUrl(),
                                            "咸鱼Flag");
                                }
                            }
                        });
                dialog.setNegativeButton("取消",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(
                                    View v) {

                            }
                        });

                dialog.show();
            }

        }

    }

    public static void download(Context context, String url, String title) {
        int abc = 0;
        // 获取存储ID
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        long downloadId = sp.getLong(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
        if (downloadId != -1L) {
            FileDownloadManager fdm = FileDownloadManager.getInstance(context);
            int status = fdm.getDownloadStatus(downloadId);
            if (status == DownloadManager.STATUS_SUCCESSFUL) {
                //启动更新界面
                Uri uri = fdm.getDownloadUri(downloadId);
                if (uri != null) {
                    if (compare(getApkInfo(context, uri.getPath()), context)) {
                        startInstall(context, uri);
                        return;
                    } else {
                        fdm.getDownloadManager().remove(downloadId);
                    }
                }
                start(context, url, title);
            } else if (status == DownloadManager.STATUS_FAILED) {
                start(context, url, title);
            } else {
                start(context, url, title);
                XLog.e("test", "apk is already downloading");
            }
        } else {
            start(context, url, title);
        }

    }

    /**
     * 获取apk程序信息[packageName,versionName...]
     *
     * @param context Context
     * @param path    apk path
     */
    private static PackageInfo getApkInfo(Context context, String path) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            return info;
        }
        return null;
    }


    /**
     * 下载的apk和当前程序版本比较
     *
     * @param apkInfo apk file's packageInfo
     * @param context Context
     * @return 如果当前应用版本小于apk的版本则返回true（都返回true,以防需要版本回滚）
     */
    private static boolean compare(PackageInfo apkInfo, Context context) {
        if (apkInfo == null) {
            return false;
        }
        String localPackage = context.getPackageName();
        if (apkInfo.packageName.equals(localPackage)) {
            try {
                PackageInfo packageInfo = context.getPackageManager().getPackageInfo(localPackage, 0);
                if (apkInfo.versionCode > packageInfo.versionCode) {
                    return true;
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    private static void start(Context context, String url, String title) {
        long id = FileDownloadManager.getInstance(context).startDownload(url,
                title, "下载完成后自动安装");
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        sp.edit().putLong(DownloadManager.EXTRA_DOWNLOAD_ID, id).apply();
       XLog.e("test", "apk start download 下载完成后自动安装" + id);
    }

//    public static void startInstall(Context context, Uri uri) {
//        Intent install = new Intent(Intent.ACTION_VIEW);
//        install.setDataAndType(uri, "application/vnd.android.package-archive");
//        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(install);
//    }


    public static void startInstall(Context context, Uri downloadFileUri) {
        Intent install = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        XLog.e("test","fileLocation:"+downloadFileUri.toString());
        if (downloadFileUri != null) {
            //  LogUtils.e("test","download 11111111111");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            File apkFile = new File(Environment.getExternalStorageDirectory() + File.separator + "咸鱼Flag.apk");
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                Uri apkUri = FileProvider.getUriForFile(context,context.getPackageName()+".fileprovider",apkFile);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
                //   LogUtils.e("test","download 22222222222221"+apkUri);
            }else{
                //    LogUtils.e("test","download 3333333331");
                install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                context.startActivity(install);
            }

               XLog.e("test","download 4444444441111111111111111");
        }
    }



}
